package com.rc.evcharger.biz.job;

import com.rc.evcharger.biz.log.ChargedProcessLogAssemble;
import com.rc.evcharger.biz.notify.NotifyStopChargeResult;
import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.common.enums.ChargePhaseEnum;
import com.rc.evcharger.common.task.PlatformTaskEnum;
import com.rc.evcharger.common.utils.DateHelper;
import com.rc.evcharger.model.order.OrderInfo;
import com.rc.evcharger.model.task.PlatformTaskSetting;
import com.rc.evcharger.redis.RedisService;
import com.rc.evcharger.service.OrderCostService;
import com.rc.evcharger.service.OrderCostServiceImpl;
import com.rc.evcharger.service.order.OrderInfoService;
import com.rc.evcharger.service.task.PlatformTaskSettingService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Create by Yang on 2021/8/28
 * 延迟结算前一天订单
 * 每日早上5点执行，结算前一天挂单订单（内部、反向订单）
 */
public class DelayBalanceJob {
    private static Logger logger = LogManager.getLogger(OrderCostServiceImpl.class);

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderCostService orderCostService;

    @Autowired
    private PlatformTaskSettingService platformTaskSettingService;

    @Autowired
    private ChargedProcessLogAssemble chargedProcessLogAssemble;

    @Autowired
    private NotifyStopChargeResult notifyStopChargeResult;

    @Autowired
    private RedisService redisService;


    public void run() {
        logger.info("超时20小时自动结算扫描订单开始执行....");

        //boolean bool = redisService.addExpire(PlatformTaskEnum.EVC_DELAY_BALANCE_TASK.getCode(), 1, 10000);
        //if (bool) {
        //    logger.info("定时请求正在充电的桩的充电数据!!,不能重复执行");
        //    return;
        //}

        //保证原子性
        if(!redisService.setIfAbsent(PlatformTaskEnum.EVC_DELAY_BALANCE_TASK.getCode(),1,10000L)){
            logger.info("每1分钟自动重新结算失败的订单接口在执行!!,不能重复执行");
            return;
        }

        //是否开启执行
        PlatformTaskSetting platformTaskSetting = platformTaskSettingService.selectByTaskType(PlatformTaskEnum.EVC_DELAY_BALANCE_TASK.getCode());
        if (platformTaskSetting == null) {
            logger.info("定时请求正在充电的桩的充电数据暂停使用!");
            return;
        }

        //查询前一天的挂单订单
        Calendar instance = Calendar.getInstance();
        //当前时间
        Date endTime = instance.getTime();

        instance.add(Calendar.DAY_OF_MONTH, -1);
        instance.set(Calendar.HOUR_OF_DAY, 0);
        instance.set(Calendar.MINUTE, 0);
        instance.set(Calendar.SECOND, 0);
        instance.set(Calendar.MILLISECOND, 0);

        Date startTime = instance.getTime();


        try {
            /**获取挂单订单**/
            List<OrderInfo> orderInfos = orderInfoService.listNotFinishedOrder(startTime, endTime);
            for (OrderInfo orderInfo : orderInfos) {
                if ((System.currentTimeMillis() - orderInfo.getStartTime().getTime()) / 1000 > SocketConstant.TIME_20_HOUR) {
                    logger.info("超过20小时，开始超时结算,对应订单号:{}", orderInfo.getOrderNum());

                    //结算超时订单
                    //orderCostService.updateOrderCostByMongdbLog(orderInfo.getOrderNum(), SocketConstant.STOP_TIMING_0XD, processLog);
                    orderCostService.updateOrderCost(orderInfo.getOrderNum(), SocketConstant.STOP_TIMING_0XD);

                    //添加日志
                    chargedProcessLogAssemble.assembleChargedProcessLog(ChargePhaseEnum.TIMING_SETTLED, orderInfo);

                    //推送订单停止状态
                    notifyStopChargeResult.notifyOrderStop(orderInfo.getOrderNum(), SocketConstant.CON0, SocketConstant.CON1, 0);
                }
            }
        } catch (Exception e) {
            logger.error("超过20小时结算异常:", e);
         }
    }


    //public void run() {
    //
    //    logger.info("mongdb结算自动扫描订单开始执行....");
    //
    //    //查询前一天的挂单订单
    //    Calendar instance = Calendar.getInstance();
    //    instance.add(Calendar.DAY_OF_MONTH, -1);
    //    instance.set(Calendar.HOUR_OF_DAY, 0);
    //    instance.set(Calendar.MINUTE, 0);
    //    instance.set(Calendar.SECOND, 0);
    //    instance.set(Calendar.MILLISECOND, 0);
    //
    //    Date startTime = instance.getTime();
    //
    //
    //    instance.set(Calendar.HOUR_OF_DAY, 23);
    //    instance.set(Calendar.MINUTE, 59);
    //    instance.set(Calendar.SECOND, 59);
    //    instance.set(Calendar.MILLISECOND, 0);
    //    Date endTime = instance.getTime();
    //
    //
    //    ChargeProcessLogVo chargeProcessLogVo = new ChargeProcessLogVo();
    //    chargeProcessLogVo.setLimit(10);
    //    chargeProcessLogVo.setOffset(0);
    //    chargeProcessLogVo.setOrderBy(1);
    //
    //
    //    try {
    //        /**获取挂单订单**/
    //        List<OrderInfo> orderInfos = orderInfoService.listNotFinishedOrder(startTime, endTime);
    //        for (OrderInfo orderInfo : orderInfos) {
    //
    //            chargeProcessLogVo.setOrderNum(orderInfo.getOrderNum());
    //
    //            int i = 0;
    //
    //            //查询mongdb最后一条充电中日志
    //            PageImpl<ChargedProcessLog> pageBySearch = chargedProcessLogService.findPageBySearch(chargeProcessLogVo);
    //            for (ChargedProcessLog processLog : pageBySearch.getContent()) {
    //                if (processLog.getPhase().equals("充电中")) {
    //
    //                    logger.info("mongdbJob开始超时结算,对应订单号:{}", orderInfo.getOrderNum());
    //
    //                    //结算超时订单
    //                    //orderCostService.updateOrderCostByMongdbLog(orderInfo.getOrderNum(), SocketConstant.STOP_TIMING_0XD, processLog);
    //                    orderCostService.updateOrderCostByMongdbLog(orderInfo.getOrderNum(), SocketConstant.STOP_TIMING_0XD, processLog);
    //
    //                    //添加日志
    //                    chargedProcessLogAssemble.assembleChargedProcessLog(ChargePhaseEnum.TIMING_SETTLED, orderInfo);
    //
    //                    //推送订单停止状态
    //                    notifyStopChargeResult.notifyOrderStop(orderInfo.getOrderNum(), SocketConstant.CON0, SocketConstant.CON1, 0);
    //                    i = 1;
    //                    break;
    //                }
    //            }
    //
    //            if (i == 1) {
    //                continue;
    //            }
    //            //处理无日志订单
    //            ChargedProcessLog chargedProcessLog = new ChargedProcessLog();
    //            chargedProcessLog.setPower(SocketConstant.CON0 + "");
    //            chargedProcessLog.setServiceAmount(SocketConstant.CON0 + "");
    //            chargedProcessLog.setElecAmount(SocketConstant.CON0 + "");
    //            chargedProcessLog.setSoc(orderInfo.getBeginSoc().toString());
    //            logger.info("mongdbJob开始超时结算,对应订单号:{}", orderInfo.getOrderNum());
    //
    //            //结算超时订单    0元订单
    //            orderCostService.updateOrderCostByMongdbLog(orderInfo.getOrderNum(), SocketConstant.STOP_TIMING_0XD, chargedProcessLog);
    //
    //            //添加日志
    //            chargedProcessLogAssemble.assembleChargedProcessLog(ChargePhaseEnum.TIMING_SETTLED, orderInfo);
    //
    //            //推送订单停止状态
    //            notifyStopChargeResult.notifyOrderStop(orderInfo.getOrderNum(), SocketConstant.CON0, SocketConstant.CON1,0);
    //        }
    //    } catch (Exception e) {
    //        logger.error("mongdb结算异常:", e);
    //    }
    //}


    public static void main(String[] args) {

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH, -1);
        instance.set(Calendar.HOUR_OF_DAY, 0);
        instance.set(Calendar.MINUTE, 0);
        instance.set(Calendar.SECOND, 0);
        instance.set(Calendar.MILLISECOND, 0);

        Date startTime = instance.getTime();


        instance.set(Calendar.HOUR_OF_DAY, 23);
        instance.set(Calendar.MINUTE, 59);
        instance.set(Calendar.SECOND, 59);
        instance.set(Calendar.MILLISECOND, 0);

        Date endTime = instance.getTime();

        System.out.println(DateHelper.dataToString(startTime, DateHelper.DATE_COMMON_FORMAT));
        System.out.println(DateHelper.dataToString(endTime, DateHelper.DATE_COMMON_FORMAT));

    }
}
